package com.wsh.lab.controller;

import com.wsh.lab.conf.JdbcConf;
import com.wsh.lab.util.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * 动态使用配置值：Spring 3.0以后
 * Spring 3.0才开始支持注解（@Value）
 *
 * @author wsh
 * @date 2021-11-02 23:15
 */
@Component
@WebServlet("hello")
public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) {
        /**
         * 乱码方案一：
         * 1、设置response获得字符流的缓冲区的编码
         * 2、通知浏览器使用的编码
         */
//        response.setCharacterEncoding("utf-8");
//        response.setHeader("Content-Type", "text/html;character=utf-8");
        /**
         * 乱码方案二：与方案一等效
         * 注意拼写“charset”，与方案一拼写不同。写错则无效果。
         */
        response.setContentType("text/html;charset=UTF-8");

        // JDBC
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            //注册驱动
            Class.forName(Constants.JDBC_DRIVER);
            //获取连接
            con = DriverManager.getConnection(Constants.JDBC_URL, Constants.JDBC_USER, Constants.JDBC_PASSWORD);
            String sql = "select Host, User from user where find_in_set(Host, ?) ";
            //获取数据库操作对象
            ps = con.prepareStatement(sql);
            //设置参数
            ps.setString(1, "%,localhost");
            rs = ps.executeQuery();
            //处理结果集
            PrintWriter writer = response.getWriter();
            int i = 1;
            while (rs.next()) {
                writer.print("第" + i + "行：Host=" + rs.getString("Host"));
                writer.print("，User=" + rs.getString("User"));
                writer.print("<br/>");
                i++;
            }
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //释放资源
            try {
                if (rs != null) {
                    rs.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                if (ps != null) {
                    ps.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                if (con != null) {
                    con.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
